import { defineStore } from 'pinia';
export const useWebsocket = defineStore('websocket', {
	persist: true, // 配置持久化
	state: () => {
		return {
			chatList: [],
		}
	},
	actions: {
		// 定义操作或者异步请求
		initWebsocket(data) {
			uni.connectSocket({
				url: data.url,
				success() {
					this.clearChatList()
				}
			})

			//建立连接
			uni.onSocketOpen((e) => {
				console.log('通讯开始')
				this.pushChatList({
					id: 'key_' + new Date().getTime(),
					content: data.welcome,
					avatar: '',
					name: '',
					role: 'system'
				})
			})

			//接收服务端消息
			uni.onSocketMessage((res) => {
				let result = JSON.parse(res.data)
				if (result.status == "created") {
					// 开始时候,往chatList里先push一个空内容的对象,用来接收内容
					this.pushChatList({
						id: 'key_' + new Date().getTime(),
						content: '',
						avatar: '',
						name: '',
						role: 'system',
						followUpList: []
					})
				}
				if (result.content) {
					if (result.type) {
						if (result.type == "answer") {
							this.saveMsg(result.content)
						} else if (result.type == "follow_up") {
							// 推荐问题
							this.pushFollowUpList({
								id: new Date().getTime(),
								content: result.content,
							})
						}
					}
				}
			})

			// 通讯异常
			uni.onSocketError((e) => {
				console.log('通讯异常：', e)
			})

			// 关闭连接
			uni.onSocketClose((e) => {
				console.log('关闭连接：', e)
			})
		},

		clearChatList() {
			this.chatList = []
		},

		pushChatList(data) {
			this.chatList.push(data)
		},

		saveMsg(data) {
			if (data) {
				this.chatList[this.chatList.length - 1].content += data
			}
		},

		// 保存推荐问题列表
		pushFollowUpList(data) {
			if (data) {
				this.chatList[this.chatList.length - 1].followUpList.push(data)
			}
		},

		sendMsg(msg) {
			this.pushChatList({
				id: 'key_' + new Date().getTime(),
				content: msg,
				avatar: '',
				name: '',
				role: 'self'
			})
			uni.sendSocketMessage({
				data: msg,
			});
		},

	}
})